home *** CD-ROM | disk | FTP | other *** search
/ Reverse Code Engineering RCE CD +sandman 2000 / ReverseCodeEngineeringRceCdsandman2000.iso / RCE / Ebooks / Thinking in C++ V2 / C04 / Nested.cpp < prev    next >
Encoding:
C/C++ Source or Header  |  2000-05-25  |  957 b   |  46 lines

  1. //: C04:Nested.cpp {O}
  2. // From Thinking in C++, 2nd Edition
  3. // Available at http://www.BruceEckel.com
  4. // (c) Bruce Eckel 1999
  5. // Copyright notice in Copyright.txt
  6. // Linked list with nesting
  7. #include "Stack.h"
  8. #include "../require.h"
  9. using namespace std;
  10.  
  11. void 
  12. Stack::Link::initialize(void* dat, Link* nxt) {
  13.   data = dat;
  14.   next = nxt;
  15. }
  16.  
  17. void Stack::initialize() { head = 0; }
  18.  
  19. void Stack::push(void* dat) {
  20.   Link* newLink = new Link();
  21.   newLink->initialize(dat, head);
  22.   head = newLink;
  23. }
  24.  
  25. void* Stack::peek() { return head->data; }
  26.  
  27. void* Stack::pop() {
  28.   if(head == 0) return 0;
  29.   void* result = head->data;
  30.   Link* oldHead = head;
  31.   head = head->next;
  32.   delete oldHead;
  33.   return result;
  34. }
  35.  
  36. void Stack::cleanup() {
  37.   Link* cursor = head;
  38.   while(head) {
  39.     cursor = cursor->next;
  40.     delete head->data; // Assumes a 'new'!
  41.     delete head;
  42.     head = cursor;
  43.   }
  44.   head = 0; // Officially empty
  45. } ///:~
  46.